<?php
namespace app\api\controller;
use think\Controller;
use app\model\Category as CategoryModel;
use app\model\Token as TokenModel;
use think\Db;

class Base extends Controller
{
    public $login_user = [];
    protected $noCheckToken = ['search'];

    public function __construct(){
        parent::__construct();
        // 验证token
        $action = $this->request->action();
        // $controller = explode('.', $this->request->controller())[2];
        // 验证token
        if (!empty($this->noCheckToken)) {
            $noCheckToken = array_map('strtolower',$this->noCheckToken);
        }else{
            $noCheckToken = [];
        }
        $access_token = $this->request->header()['x-access-token'];
        $access_token = '7D9F933BC7B84B33A757D578252CC9B8';
        if ( !in_array($action, $noCheckToken) || !empty($access_token) ) {
            if ( empty($access_token) ) {
                exception('token不能为空',9000);
            }
            $token = TokenModel::where('access_token',$access_token)->find();
            if ( empty($token) ) {
                exception('token无效',9000);
            }
            if ( time() > strtotime($token['expiry_time']) ) {
                // exception('token已过期',9000);
            }

            $this->login_user = [
                'openid'=>$token['openid'],
                'user_id'=>$token['user_id']
            ];
        }
    }

    public function search($keyword){
        $keyword = trim($keyword);
        if ( empty($keyword) ) {
            return apiResult('5000','请输入关键字');
        }
        $data = [
            'activity'=>[],
            'member'=>[],
            'news'=>[],
            'resource'=>[]
        ];
        $activity = Db::name('wx_activity')->where('name','like','%'.$keyword.'%')->select();
        foreach ($activity as $k => $vo) {
            if (!empty($vo['tags'])) {
                $activity[$k]['tags'] = explode(',',$vo['tags']);
            }else{
                $activity[$k]['tags'] = [];
            }
            
            if (!empty($user_id)) {
                $activity[$k]['is_apply'] = Db::name('wx_uactivity')->where([
                    ['user_id','=',$user_id],
                    ['status','<>',-1],
                    ['wx_activity_id','=',$vo['id']]
                ])->count() > 0 ? 1 : 0;
            }
            
            $user_ids = Db::name('wx_uactivity')->where([
                ['status','<>',-1],
                ['wx_activity_id','=',$vo['id']]
            ])->column('user_id');
            $users = [];
            if (!empty($user_ids)) {
                $users = Db::name('user')->field('id,nickname,headimgurl')->where('id','in',$user_ids)->select();
            }
            $activity[$k]['users'] = $users;
        }
        if (!empty($activity)) {
            $data['activity'] = $activity;
        }


        $member = Db::name('wx_member')->where('name','like','%'.$keyword.'%')->select();
        if (!empty($member)) {
            $data['member'] = $member;
        }


        $news = Db::name('wx_news')->where('name','like','%'.$keyword.'%')->select();
        foreach ($news as $k => $vo) {
            if (!empty($vo['tags'])) {
                $news[$k]['tags'] = explode(',',$vo['tags']);
            }else{
                $news[$k]['tags'] = [];
            }

            if (!empty($vo['images'])) {
                $news[$k]['images'] = explode(',',$vo['images']);
            }else{
                $news[$k]['images'] = [];
            }
        }
        if (!empty($news)) {
            $data['news'] = $news;
        }

        $resource = Db::name('wx_resource')->where('name','like','%'.$keyword.'%')->select();
        foreach ($resource as $k => $vo) {
            if (!empty($vo['tags'])) {
                $resource[$k]['tags'] = explode(',',$vo['tags']);
            }else{
                $resource[$k]['tags'] = [];
            }

            if (!empty($vo['images'])) {
                $resource[$k]['images'] = explode(',',$vo['images']);
            }else{
                $resource[$k]['images'] = [];
            }
        }
        if (!empty($resource)) {
            $data['resource'] = $resource;
        }

        return apiResult('2000','获取成功',$data);
    }

    /**
     * [uploadFile description]
     * @Author   CCH
     * @DateTime 2020-06-07T17:25:30+0800
     * @return   [description]
     */
    public function uploadFile(){
        $file = $_FILES['file'];
        if (empty($file)) {
            return apiResult('5000','未检测到图片');
        }
        $ext = explode(".", $file['name']);//拆分获取图片名
        $ext = $ext[count($ext) - 1];//取图片的后缀名
        $ext = strtolower($ext);
        $types = ["jpg", "gif", 'png', 'bmp','jpeg','pdf','doc','docx','xls','xlsx','txt'];
        if (!in_array($ext, $types)) {
            return apiResult('5000','文件格式不支持，请上传标准图片文件');
        }
        $result = uploadFile($file['name'],$file['tmp_name'],date('Ymd').'/');

        if ($result['status'] == 1) {
            return apiResult('2000','上传成功',[
                'extension'=>$ext,
                'savename'=>$result['data'],
                'filename'=>$file['name']
            ]);
        }else{
            return apiResult('5000',$result['msg']);
        }
    }

    /**
     * 生成二维码
     * @Author   CCH
     * @DateTime 2020-06-07T17:25:21+0800
     * @param    $path  路径
     * @param    $width 宽度
     * @return   返回图片base数据给前端小程序，直接放前端img src即可显示
     */
    public function createQrCode($path,$width=150){
        $config = config('config.wxparam');
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
        $access_token = httpRequest( $access_token_url );
        $access_token = json_decode($access_token,true); 
        if (empty($access_token['access_token'])) {
            return apiResult('5000','access_token获取失败');
        }

        $qcode ="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token['access_token'];
        $param = json_encode(array("path"=>$path,"width"=> 150));
        $result = httpRequest( $qcode, $param , "POST");
        if (!empty($result)) {

            return apiResult('2000','二维码生成成功',"data:image/jpeg;base64,".base64_encode( $result ));
        }else{
            return apiResult('5000','二维码生成失败');
        }
    }

    /**
     * 生成二维码
     * @Author   CCH
     * @DateTime 2020-06-07T17:25:21+0800
     * @param    $path  路径
     * @param    $width 宽度
     * @return   返回图片base数据给前端小程序，直接放前端img src即可显示
     */
    public function createQrCodeOss($path,$width=150){
        $config = config('config.wxparam');
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
        $access_token = httpRequest( $access_token_url );
        $access_token = json_decode($access_token,true); 
        if (empty($access_token['access_token'])) {
            return apiResult('5000','access_token获取失败');
        }

        $qcode ="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token['access_token'];
        $param = json_encode(array("path"=>$path,"width"=> 150));
        $result = httpRequest( $qcode, $param , "POST");
        if (!empty($result)) {
            $image = uploadFileString($result,'appraisal/app/');
            if ($image['status'] == 1) {
                return apiResult('2000','二维码生成成功',$image['data']);
            }else{
                return apiResult('5000','上传失败');
            }
        }else{
            return apiResult('5000','二维码生成失败');
        }
    }

    public function createUnlimitedCodeOss($path,$scene,$width=150){
        $config = config('config.wxparam');
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
        $access_token = httpRequest( $access_token_url );
        $access_token = json_decode($access_token,true); 
        if (empty($access_token['access_token'])) {
            return apiResult('5000','access_token获取失败');
        }

        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token['access_token'];
        $param = json_encode(array("path"=>$path,'scene'=>$scene,"width"=> 150));
        $result = httpRequest( $qcode, $param , "POST");
        if (!empty($result)) {
            return apiResult('2000','二维码生成成功',"data:image/jpeg;base64,".base64_encode( $result ));
        }else{
            return apiResult('5000','二维码生成失败');
        }
        // if (!empty($result)) {
        //     $image = uploadFileString($result,'bwc/app/');
        //     if ($image['status'] == 1) {
        //         return apiResult('2000','二维码生成成功',$image['data']);
        //     }else{
        //         return apiResult('5000','上传失败');
        //     }
        // }else{
        //     return apiResult('5000','二维码生成失败');
        // }
    }

}
